package com.example.servletdemo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对请求的接口进行日志简单记录
 */
//@WebFilter(filterName = "logFilter",urlPatterns = "/*",dispatcherTypes = DispatcherType.FORWARD)
public class LogFilter  implements Filter {

    private String filterName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        filterName = filterConfig.getFilterName();
        System.out.println(filterName+":init");
    }

    @Override
    public void destroy() {
        System.out.println(filterName+":destroy");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //对resquest的请求数据进行增强
        System.out.println("filterName---------------------开始执行中-------------------------");
        //统一设置编码格式
//        servletResponse.setContentType("text/html;charset=utf-8");

        //接口名称
        String requestURI = request.getRequestURI();

        long  startTime=System.currentTimeMillis();//请求开始时间
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
        long endTime = System.currentTimeMillis();//请求结束时间

        //对response的响应数据进行增强
        System.out.println("请求地址："+requestURI+" 耗时："+(endTime-startTime)+"ms");
        System.out.println("filterName---------------------执行完成-------------------------");
    }
}
